#include<iostream>
#include <queue>
#include <string>
#include <unordered_map>
#include <unordered_set>
using namespace std;
class Solution {
public:
    string alienOrder(vector<string>& words) {
        unordered_map<char, unordered_set<char>> graph;
        unordered_map<char, int> indegree;
        for (const string& word : words) {
            for (char ch : word) {
                indegree[ch] = 0;
            }
        }
        for (int i = 0; i < words.size() - 1; i++) {
            const string& w1 = words[i];
            const string& w2 = words[i + 1];
            int min_len = min(w1.length(), w2.length());
            if (w1.length() > w2.length() && w1.substr(0, min_len) == w2.substr(0, min_len)) {
                return "";
            }

            for (int j = 0; j < min_len; j++) {
                if (w1[j] != w2[j]) {
                    if (graph[w1[j]].find(w2[j]) == graph[w1[j]].end()) {
                        graph[w1[j]].insert(w2[j]);
                        indegree[w2[j]]++;
                    }
                    break;
                }
            }
        }
        queue<char> q;
        for (const auto& pair : indegree) {
            if (pair.second == 0) {
                q.push(pair.first);
            }
        }

        string result;
        while (!q.empty()) {
            char ch = q.front();
            q.pop();
            result += ch;

            for (char neighbor : graph[ch]) {
                indegree[neighbor]--;
                if (indegree[neighbor] == 0) {
                    q.push(neighbor);
                }
            }
        }
        if (result.length() == indegree.size()) {
            return result;
        }
        else {
            return "";
        }
    }
};